//
//  XSJComposeViewController.swift
//  weiBo项目准备
//
//  Created by 鲜世杰 on 16/5/19.
//  Copyright © 2016年 鲜世杰. All rights reserved.
//

import UIKit

import SVProgressHUD

class XSJComposeViewController: UIViewController, UITextViewDelegate {

    
    private lazy var textView : XSJComposeTextView = {
    
        let view = XSJComposeTextView()
        view.delegate = self
        view.font = UIFont.systemFontOfSize(14)

        view.placeHolder = "分享新鲜事..."
//        view.font = UIFont.systemFontOfSize(18)
        view.alwaysBounceVertical = true
        return view
    }()
    
    private lazy var toolBar : XSJComposeToolBar = {
    
       let view = XSJComposeToolBar(frame: CGRectZero)
        return view
    }()
        
    private lazy var pictureView: XSJComposePictureView = {
        let view = XSJComposePictureView()
        
        view.backgroundColor = self.view.backgroundColor
        
        return view
    }()

    private lazy var emoticonKeyboard: XSJEmoticonKeyBoard = {
        let view = XSJEmoticonKeyBoard()
        
        view.frame.size = CGSize(width: self.textView.frame.size.width, height: 216)
        return view
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChageFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didSectedEmoticon:", name: DidSeletedEmoticonNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didSelectedDeleteEmoticon", name: DidSelectedDeleteEmoticonButtonNotification, object: nil)

        setUpUI()
    }
    
    private func setUpUI() {
    view.backgroundColor = UIColor.whiteColor()
        setupNavUI()
        view.addSubview(textView)
        
        textView.addSubview(pictureView)

        view.addSubview(toolBar)
        
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(100)
            make.centerX.equalTo(textView)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(textView.snp_width).offset(-20)
        }

        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.height.equalTo(44)
        
    }
        
        toolBar.didSeletedButtonClosure = { [weak self](type: XSJComposeToolBarButtonType) in
        
            switch type {
            case .Picture:
                print("Picture")
                self?.didSelectedPicture()
            case .Mention:
                print("Mention")
                
            case .Trend:
                print("Trend")
                
            case .Emoticon:
                print("Emoticon")
              self?.didSelectedEmoticon()
            case .Add:
                print("Add")
            }
            
        }
        
        pictureView.didSelectAddImageClosure = { [weak self] in
        
            self?.didSelectedPicture()
            
        }
    
    }
    
    private func setupNavUI() {
    
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", fontSize: 15, target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        navigationItem.rightBarButtonItem?.enabled = false
        navigationItem.titleView = titleLabel
    }
    @objc private func cancelAction() {
        
        dismissViewControllerAnimated(true, completion: nil)
        self.view.endEditing(true)
        
    }
    
    

    private lazy var rightButton : UIButton = {
    
        let button = UIButton()
        button.setTitle("保存", forState: .Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        button.addTarget(self, action: "sendAction", forControlEvents: .TouchUpInside)
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)

        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        button.frame.size = CGSize(width: 45, height: 30)

        button.enabled = false
        return button
    }()
    
    @objc private func sendAction() {
        if pictureView.images.count > 0 {
            upload()
        } else{
            update()
        }

       

    }
    
    private func update() {
        
        let accesstoken = XSJUserAccountViewModel.sharedUserAccount.accessToken!
        let status = textView.emticonText //textView.text!

//        print(accesstoken)
        
        SVProgressHUD.show()
        
        XSJNetWorkTools.sharedTools.update(accesstoken, status: status) { (response, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("网络请求异常")
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("发送成功")
        }
    }
    private func upload() {
        
        let accesstoken = XSJUserAccountViewModel.sharedUserAccount.accessToken!
        let status = textView.emticonText //textView.text!

        
        SVProgressHUD.show()
        
  
        let image = pictureView.images.first!
        
        XSJNetWorkTools.sharedTools.upload(accesstoken, status: status, image: image, callBack: { (response, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("网络异常")
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("发送成功")
        })
        
        
        
    }
    
    @objc private func keyboardChageFrame(noti: NSNotification) {
        
        
        let keyboardFrame = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"]! as! NSValue).CGRectValue()
        
        
        let animationDuration = (noti.userInfo!["UIKeyboardAnimationDurationUserInfoKey"]! as! NSNumber).doubleValue

    
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(keyboardFrame.origin.y - view.frame.size.height)

        }
        UIView.animateWithDuration(animationDuration) { () -> Void in
            self.view.layoutIfNeeded()

        }
    
    }
    
    private lazy var titleLabel : UILabel = {
    
        let label = UILabel(textColor: UIColor.darkGrayColor(), fontSize: 17)
        if let name = XSJUserAccountViewModel.sharedUserAccount.userAccount?.name{
        
            let title : String = "发微博\n\(name)"
            let range = (title as NSString).rangeOfString(name)
            let attributedStr = NSMutableAttributedString(string: title)
            attributedStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: range)
            attributedStr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(15), range: range)
            label.attributedText = attributedStr
            
           
        }else {
        
            label.text = "发微博"
            
        }
        label.numberOfLines = 0
        label.textAlignment = .Center
        label.sizeToFit()

        
        return label
    }()
    
    
    @objc private func didSelectedDeleteEmoticon() {
    
        textView.deleteBackward()
        
    }
    
    
    @objc private func didSectedEmoticon(noti: NSNotification) {
        

        
        guard let emoticon = noti.object as? XSJEmoticon else {
        
            return
            
        }
        textView.insertEmoticon(emoticon, font: textView.font!)
        
        
    }

    
    func textViewDidChange(textView : UITextView) {
    navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        
    }
    
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        
        self.view.endEditing(true)
    }
    
    deinit {
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
        
        
        
    }

    
}
extension XSJComposeViewController: UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    
    func didSelectedEmoticon() {
        
        if textView.inputView == nil {
        
            textView.inputView = emoticonKeyboard
         toolBar.showEmoticonIcon(true)
        }else{
        
            textView.inputView = nil
            toolBar.showEmoticonIcon(false)

        }
        textView.becomeFirstResponder()
        textView.reloadInputViews()
    }

    
    func didSelectedPicture() {
        let pictureVc = UIImagePickerController()
        
        pictureVc.delegate = self
        
        if UIImagePickerController.isSourceTypeAvailable(.Camera)
        {
        
            pictureVc.sourceType = .Camera
            
        }else{
        
            pictureVc.sourceType = .PhotoLibrary
        
        }
        if UIImagePickerController.isCameraDeviceAvailable(.Front)
        {
            print("前置摄像头可用")
        } else if UIImagePickerController.isCameraDeviceAvailable(.Rear) {
            print("后置摄像头可用")
        } else {
            print("摄像头不可用")
        }

        presentViewController(pictureVc, animated: true, completion: nil)
    }
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
//        pictureView.addImage(image)

        let scaleImage = image.scaleImageWithWidth(300)
        
        pictureView.addImage(scaleImage)
        
        picker.dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        
        picker.dismissViewControllerAnimated(true, completion: nil)

    }
}